package com.woniuxy.huayoung.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.woniuxy.huayoung.annotations.RequirePermission;
import com.woniuxy.huayoung.entity.Attention;
import com.woniuxy.huayoung.entity.Perm;
import com.woniuxy.huayoung.entity.Role;
import com.woniuxy.huayoung.entity.User;
import com.woniuxy.huayoung.result.ResponseResult;
import com.woniuxy.huayoung.service.RoleService;
import com.woniuxy.huayoung.service.UserService;
import com.woniuxy.huayoung.utils.JwtUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {
    //日志对象
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    //对象注入
    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private JavaMailSender mailSender;


    @PostMapping("/login")
    //@RequestBody 到时候前端返回json时添加上
    public ResponseResult<User> login(@RequestBody User user, HttpServletResponse response, HttpServletRequest request){
        logger.error(user.toString());

        //得到token
        String token = request.getHeader("authorization");
        if (token != null){
            return new ResponseResult<>(201,"请勿重复登录",null);
        }
        logger.debug(user.toString());
        //给输入的密码加密
        String newpwd = new SimpleHash("MD5",user.getPwd(),user.getTelephone(),100).toString();
        user.setPwd(newpwd);

        //逻辑：用账号查询出结果，然后进行对比   假设查询出来
        User result  = userService.login(user.getTelephone());

        if (result != null && user.getTelephone().equals(result.getTelephone()) && newpwd.equals(result.getPwd())){
            logger.debug("登录成功!");

            //查询角色信息绑定到result
            Integer uid = result.getId();//用户id
            Role role = roleService.findByUid(uid);
            logger.debug(role.toString());
            result.setRole(role);


            //生成一个token（JWT）然后返回给前端浏览器
            token = JwtUtil.generateToken(user.getTelephone());

            //将token放到响应头
            response.setHeader("authorization",token);
            //将该响应头暴露给第三方
            response.setHeader("Access-Control-Expose-Headers","authorization");

            return new ResponseResult<>(200,"success",result);
        }else {
            logger.debug("登录失败!");
            return new ResponseResult<>(500,"账号或者密码有误",null);
        }
    }

    //注册
//    @RequestMapping("/regist")
//    public void regist (User user){
//        //加密
//        String newpwd = new SimpleHash("MD5",user.getPwd(),user.getTelephone(),100).toString();
//
//
//        boolean result = userService.regist(user.getTelephone(),newpwd);
//    }

    //查询个人信息
    @GetMapping("/findByToken")
    //@RequirePermission("admin:select")
    public ResponseResult<User> findByToken(HttpServletRequest request){
        //得到token
        String token = request.getHeader("authorization");
        User user = userService.findByTelephone(JwtUtil.getAccount(token));
        ResponseResult<User> result = new ResponseResult<>(200,"查询成功",user);
        logger.debug(user.toString());
        return  result;
    }

    //通过id查询用户基本信息
    @GetMapping("/findById")
    public ResponseResult<User> findById(@RequestParam("id") Integer id){
        logger.debug(id.toString());
        User user = userService.findById(id);
        return new ResponseResult<User>(200, "查询用户成功", user);
    }

    //修改个人信息
    @PostMapping("/updateUser")
    public ResponseResult<String> updateUser(@RequestBody User user){
        int i = userService.updateUser(user);
        if(i != 0){
            return new ResponseResult<String>(200,"修改成功",null);
        }
        return new ResponseResult<String>(500,"修改出错",null);
    }

    //查询关注的对象
    @GetMapping("/findAttentions")
    public ResponseResult<Attention> findAtteneions(HttpServletRequest request){
        //得到token
        String token = request.getHeader("authorization");
        Attention attention = userService.findAttentions(token);
        //List<User> users = attention.getUsers();
        if(attention != null){
            return new ResponseResult<Attention>(200,"成功",attention);
        }
        return new ResponseResult<Attention>(500,"失败",null);
    }

    //取消关注的用户
    @RequestMapping("/cancelAttention")
    public ResponseResult<Attention> cancelAttention(Integer attentionedUid, Integer attentionUid){
        logger.debug(attentionedUid.toString());
        logger.debug(attentionUid.toString());
        Attention attention = userService.cancelAttention(attentionedUid, attentionUid);
        if(attention.getAttentionUid() != 0){

            return new ResponseResult<Attention>(200,"删除成功",attention);
        }
        return new ResponseResult<Attention>(500,"失败",null);

    }

    //上传头像
    @RequestMapping("/uploadHeadPortrait")
    public ResponseResult<String> uploadHeadPortrait(@RequestParam("files") MultipartFile file, HttpServletRequest request) throws Exception{

        //得到token
        String token = request.getHeader("authorization");
        String telephone = JwtUtil.getAccount(token);
        //
        String path="D:\\huayoung\\headportrait";

        //创建文件
        File dir=new File(path);
        if(!dir.exists()){
            dir.mkdirs();
        }

        String id = UUID.randomUUID().toString();
        String fileName=file.getOriginalFilename();

        String img=id+fileName.substring(fileName.lastIndexOf("."));//zhao.jpg
        FileOutputStream imgOut=new FileOutputStream(new File(dir,img));//根据 dir 抽象路径名和 img 路径名字符串创建一个新 File 实例。
        /* System.out.println(file.getBytes());*/
        imgOut.write(file.getBytes());//返回一个字节数组文件的内容
        imgOut.close();

        //将头像的图片名存到数据库
        int i = userService.updateHeadPortrait(img,telephone);
        if(i != 0){
            return new ResponseResult<String>(200,"修改成功",img);
        }
        //如果上传失败，就重新去数据库查头像的图片名
        //img = userService.findHeadPortrait(telephone);
        return new ResponseResult<String>(500,"修改失败",null);
    }



    //获取验证码
    //获取邮箱验证码
    @PostMapping("getCode")
    public ResponseResult<Object> cancelAttention(@RequestBody User user){

        if (user.getEmail() == null || user.getEmail().equals("")){
            return new ResponseResult().setCode(500).setMessage("邮箱不能为空").setData("滚");
        }
//        生成4位数字验证码
        String emailCode = RandomUtil.randomNumbers(4);
        logger.debug("email-code:"+emailCode);

//        配置发送邮箱
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("2318664121@qq.com");
        message.setTo(user.getEmail());
        logger.debug(user.getEmail());
        message.setSubject("邮箱验证");
        message.setText("欢迎成为花样旅游会员，你的验证码为，"+emailCode+"，请在2分钟类注册");
//        邮箱发送
        mailSender.send(message);
//            缓存数据
        redisTemplate.opsForValue().set("email-code"+user.getEmail(),emailCode,120, TimeUnit.SECONDS);

        return new ResponseResult<>().setCode(200).setData(new HashMap<String,String>().put("emailCode",emailCode));
    }

//    注册接口
    @PostMapping("/regist")
    @ApiOperation("用户注册接口")
    public ResponseResult regist(@RequestBody Map<String,String> map) {
        String phone = map.get("phone");
        String email = map.get("email");
        String pwd = map.get("pwd");
        String emailCode = map.get("emailCode");

        if (phone == null || email == null || pwd == null || emailCode == null) {
            return new ResponseResult().setCode(500).setData("参数填写不完整");
        }
        String emailCode1 = redisTemplate.opsForValue().get("email-code" + email);
        if (!(emailCode1 == null || emailCode1.equals(emailCode))) {
            return new ResponseResult().setCode(500).setData("验证码过期或错误");
        }
        User user = new User();

        //加密
        String newpwd = new SimpleHash("MD5",pwd,phone,100).toString();

        user.setTelephone(phone);
        user.setEmail(email);
        user.setPwd(newpwd);
        user.setDel(0);

        userService.insertUser(user);
        return new ResponseResult().setCode(200).setData("成功");
    }

    //管理员查询所有用户信息
    @GetMapping("/findAll")
    public ResponseResult<List<User>> findAll(){
        List<User> users = userService.findAll();
        return new ResponseResult<List<User>>(200,"查询成功",users);
    }

    /*
     * @Description:查询所有是管理员角色的user
     * @Author: zhangyong
     * @Date: 2021/7/26 0026
     * @param rid:rid为1是管理员角色
     * @Return: com.woniuxy.huayoung.result.ResponseResult<java.util.List<com.woniuxy.huayoung.entity.User>>
     **/
    @GetMapping("/findadmin")
    public ResponseResult<List<User>> findAllAdminbyRid(){
        //Integer rid = 1;
        List<User> admins = userService.findAllAdminbyRid();
        return new ResponseResult<List<User>>(200,"查询所有管理员成功",admins);
    }

    /*
     * @Description:根据用户id去修改del状态码
     * @Author: zhangyong
     * @Date: 2021/7/27 0027
     * @param id: 用户id
     * @Return: com.woniuxy.huayoung.result.ResponseResult<java.lang.Object>
     **/
    @PostMapping("/deladmin")
    public ResponseResult<Object> delAdmin(@RequestBody Map<String, Integer> map){
        Integer id = map.get("id");
        logger.debug(id.toString());
        Boolean aBoolean = userService.delAdmin(id);
        logger.debug(aBoolean.toString());
        if(aBoolean){
            return new ResponseResult<>(200," 修改管理员del状态成功",null);
      }else{
            return new ResponseResult<>(500," 修改管理员del状态失败",null);
        }
    }

    /*
     * @Description:根据user的id去修改信息
     * @Author: zhangyong
     * @Date: 2021/7/27 0027
     * @param user: user 对象去接收前端传的参数
     * @Return: com.woniuxy.huayoung.result.ResponseResult<java.lang.Object>
     **/
    @PostMapping("/updateadmin")
    public ResponseResult<Object> updateAdmin(@RequestBody User user){
        System.out.println(user);
        int i = userService.updateAdmin(user);
         if(i == 1){
            return new ResponseResult<>(200," 修改管理员信息成功",null);
        }else{
            return new ResponseResult<>(500," 修改管理员信息失败",null);
       }
    }

    /*
     * @Description:查询所有的perms
     * @Author: zhangyong
     * @Date: 2021/7/28 0028
     * @Return: com.woniuxy.huayoung.result.ResponseResult<java.util.List<com.woniuxy.huayoung.entity.Perm>>
     **/
    @GetMapping("/findallperms")
    public  ResponseResult<List<Perm>> findAllPerms(){
        List<Perm> allPerms = userService.findAllPerms();
        return new ResponseResult<>(200," 查询所有的权限返回成功",allPerms);
    }
}
